//
//  AppDelegate.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/5/24.
//

import UIKit
import CoreData
import IQKeyboardManagerSwift
import AMapFoundationKit

public protocol SelfAware: AnyObject {
    static func awake()
}
class NothingToSeeHere {
    static func harmlessFunction(){
        let typeCount = Int(objc_getClassList(nil, 0))
        let types = UnsafeMutablePointer<AnyClass>.allocate(capacity: typeCount)
        let autoreleaseintTypes = AutoreleasingUnsafeMutablePointer<AnyClass>(types)
        objc_getClassList(autoreleaseintTypes, Int32(typeCount))
        for index in 0..<typeCount {
            (types[index] as? SelfAware.Type)?.awake()
        }
        types.deallocate()
    }
}

extension UIApplication {
    private static let runOnce:Void = {
        NothingToSeeHere.harmlessFunction()
    }()
    open override var next: UIResponder? {
        UIApplication.runOnce
        return super.next
    }
}

@main

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var userId: String = ""
    var groupId: String = ""
    var deviceToken: Data?
    


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
       
        // 设置当前网络环境
        BHHTTPEnvironment.shared.currentEnv = .Developer

        // 设置SVProgressHUD的交互
        SVProgressHUD.setHapticsEnabled(false)
        SVProgressHUD.setDefaultMaskType(.black)
        
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.enableAutoToolbar = true
        
        self.window = UIWindow.init(frame: UIScreen.main.bounds)
        self.window?.backgroundColor = .white;
    
        let launchVC = BHLaunchAdViewController.init()
        let nav = BHNavigationController.init(rootViewController: launchVC)
        
        self.window?.rootViewController = nav;
        
        self.window?.makeKeyAndVisible()
        
        // 注册高德地图
        self.registerAMap()
 
        // 注册腾讯IM
        self.registerIMNotification()
        
        // 注册友盟
        self.registerUMeng(launchOptions: launchOptions)

        return true
    }


    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        if url.absoluteString.contains(String.wechat_appId) {
            let wxResult = WXApi.handleOpen(url, delegate: self)
            return wxResult
        }
        if url.host == "safepay" { // 支付宝
            if url.absoluteString.contains("auth_code=") {
                let resultArray = url.absoluteString.components(separatedBy: "&")
                for subResult in resultArray {
                    if subResult.count > 10 && subResult.hasPrefix("auth_code=") {
                        let authCode = subResult.id_subString(from: 10)
                        DPAlipayManager.init().bindAlipay(authCode)
                        break
                    }
                }
            }else {
                AlipaySDK.defaultService()?.processOrder(withPaymentResult: url, standbyCallback: nil)
            }
            
        }else {
            let result = UMSocialManager.default()?.handleOpen(url, options: options) ?? false

            return result
        }
        return true
    }
    
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        
        if userActivity.webpageURL != nil {
            if userActivity.webpageURL!.absoluteString.contains(String.wechat_appId) {
                let wxResult = WXApi.handleOpenUniversalLink(userActivity, delegate: self)
                return wxResult
            }
        }
        
        let result = UMSocialManager.default()?.handleUniversalLink(userActivity, options: nil) ?? false
        
        if result == false {
            // 其他sdk回调
        }
        return result
    }
}

//MARK: 注册高德
extension AppDelegate {
    func registerAMap()  {
        AMapServices.shared().apiKey = String.aMapKey
    }
}

//注册友盟
extension AppDelegate {
    // 注册友盟
    func registerUMeng(launchOptions: [UIApplication.LaunchOptionsKey:Any]?) {
        UMConfigure.initWithAppkey(String.UMengKey, channel: "APP Store")
        
        UMSocialGlobal.shareInstance()?.universalLinkDic = [1:String.universalUrl,
                                                            2:String.universalUrl]

//
        UMSocialManager.default()!.setPlaform(.wechatSession, appKey: String.wechat_appId, appSecret: String.wechat_appSecret, redirectURL: "http://mobile.umeng.com/social")
//
        UMSocialManager.default()!.setPlaform(.wechatTimeLine, appKey: String.wechat_appId, appSecret: String.wechat_appSecret, redirectURL: nil)
    }
}


// MARK: 注册极光
extension AppDelegate {
    // 注册极光推送
    func registerJPush(launchOptions: [UIApplication.LaunchOptionsKey:Any]?) {
        let push = JPUSHRegisterEntity.init()
        push.types =  1 << 0 | 1 << 1 | 1 << 2
        JPUSHService.register(forRemoteNotificationConfig: push, delegate: self)
    }
}
// 极光推送代理
extension AppDelegate: JPUSHRegisterDelegate {
    func jpushNotificationAuthorization(_ status: JPAuthorizationStatus, withInfo info: [AnyHashable : Any]!) {
        
    }
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
            
            let userInfo = notification.request.content.userInfo
            if notification.request.trigger is UNPushNotificationTrigger {
                JPUSHService.handleRemoteNotification(userInfo)
            }
            // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
            completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue))
        }
        
        @available(iOS 10.0, *)
        func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
            let userInfo = response.notification.request.content.userInfo
            if response.notification.request.trigger is UNPushNotificationTrigger {
                JPUSHService.handleRemoteNotification(userInfo)
            }
            // 系统要求执行这个方法
            completionHandler()
        }
        
        //点推送进来执行这个方法
        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
            JPUSHService.handleRemoteNotification(userInfo)
            
            // 腾讯IM的处理
            self.redealIMMessage(dic: userInfo)
            
            completionHandler(UIBackgroundFetchResult.newData)
            
        }
    
        //获取token 失败
        func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { //可选
            print("did Fail To Register For Remote Notifications With Error: \(error)")
        }
        func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification?) {
            print("hello")
        }
    
}


// MARK: 程序唤起和后台
extension AppDelegate {
    func applicationDidBecomeActive(_ application: UIApplication) {
        BHCache.save_appActiveTime(timeValue: Date.currentTimeValue)
        
        NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: String.applicationActiveNotificationKey), object: nil)
    }
    
    func applicationWillResignActive(_ application: UIApplication) {
        BHCache.save_appSleepTime(timeValue: Date.currentTimeValue)
        
        NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: String.applicationSleepNotificationKey), object: nil)
    }
}

extension AppDelegate {
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        self.deviceToken = deviceToken
    }
}

// MARK: 微信代理
extension AppDelegate: WXApiDelegate {
    func onResp(_ resp: BaseResp) {
        
    }
}

// MARK: 腾讯云IM
extension AppDelegate: V2TIMSDKListener {
    func onConnecting() {
        
    }
    
    // 踢下线
    func onKickedOffline() {
        
        BHMeUserInfoModel.shared.clearUser()
        BHCommonTool.showAlertWith(showVC: nil, title: "提示", message: "您的账号在他处登录，请重新登录", okBtn: "立即登录", cancel: "取消") { (goLogin) in
            if goLogin == true {
                let currentVC = BHBaseViewController.currentViewController
                if currentVC is BHLaunchAdViewController {
                    let loginVC = BHLoginViewController.init()
                    DispatchQueue.main.async {
                        BHNavigationController.currentNavigationController?.pushViewController(loginVC, animated: true)
                    }
                }else {
                    BHRouter.shared.bh_gologin()
                }
            }
        }
    }
    
    func onConnectSuccess() {
        
    }
    
    func onUserSigExpired() {
        
    }
    
    func onConnectFailed(_ code: Int32, err: String!) {
        
    }
    
    func onSelfInfoUpdated(_ Info: V2TIMUserFullInfo!) {
        
    }
}



